package com.coursehub.course.controller;

import com.coursehub.course.dto.ClassesCreateDto;
import com.coursehub.course.entity.Classes;
import com.coursehub.course.service.ClassesService;
import com.coursehub.shared.dto.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.List;

/**
 * 班级管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/classes")
@RequiredArgsConstructor
@Validated
public class ClassesController {
    
    private final ClassesService classesService;
    
    /**
     * 创建班级
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Classes>> createClass(@Valid @RequestBody ClassesCreateDto createDto) {
        log.info("创建班级请求: {}", createDto.getClassesName());
        Classes classes = classesService.createClass(createDto);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(ApiResponse.success(classes, "班级创建成功"));
    }
    
    /**
     * 根据ID获取班级
     */
    @GetMapping("/{classesId}")
    public ResponseEntity<ApiResponse<Classes>> getClassById(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId) {
        Classes classes = classesService.getClassById(classesId);
        return ResponseEntity.ok(ApiResponse.success(classes));
    }
    
    // ====================== 统计分析相关API ======================
    
    /**
     * 根据班级ID获取班级课程ID
     */
    @GetMapping("/{classesId}/course/id")
    public ResponseEntity<ApiResponse<String>> getCourseIdByClassId(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId) {
        String courseId = classesService.getCourseIdByClassId(classesId);
        return ResponseEntity.ok(new ApiResponse<>(200, "Success", courseId, System.currentTimeMillis()));
    }
    
    /**
     * 根据班级ID获取所有学生ID
     */
    @GetMapping("/{classesId}/students/ids")
    public ResponseEntity<ApiResponse<List<String>>> getStudentIdsByClassId(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId) {
        List<String> studentIds = classesService.getStudentIdsByClassId(classesId);
        return ResponseEntity.ok(ApiResponse.success(studentIds));
    }
    
    /**
     * 获取所有班级
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<Classes>>> getAllClasses() {
        List<Classes> classes = classesService.getAllClasses();
        return ResponseEntity.ok(ApiResponse.success(classes));
    }
    
    /**
     * 根据课程ID获取班级列表
     */
    @GetMapping("/course/{courseId}")
    public ResponseEntity<ApiResponse<List<Classes>>> getClassesByCourseId(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId) {
        List<Classes> classes = classesService.getClassesByCourseId(courseId);
        return ResponseEntity.ok(ApiResponse.success(classes));
    }
    
    /**
     * 更新班级信息
     */
    @PutMapping("/{classesId}")
    public ResponseEntity<ApiResponse<Classes>> updateClass(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId,
            @Valid @RequestBody ClassesCreateDto updateDto) {
        log.info("更新班级请求: {}", classesId);
        Classes classes = classesService.updateClass(classesId, updateDto);
        return ResponseEntity.ok(ApiResponse.success(classes, "班级更新成功"));
    }
    
    /**
     * 删除班级
     */
    @DeleteMapping("/{classesId}")
    public ResponseEntity<ApiResponse<Void>> deleteClass(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId) {
        log.info("删除班级请求: {}", classesId);
        classesService.deleteClass(classesId);
        return ResponseEntity.ok(ApiResponse.success("班级删除成功"));
    }
    
    /**
     * 根据班级名称搜索班级
     */
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<List<Classes>>> searchClasses(
            @RequestParam(required = false) String classesName) {
        List<Classes> classes;
        
        if (classesName != null) {
            classes = classesService.searchClassesByName(classesName);
        } else {
            classes = classesService.getAllClasses();
        }
        
        return ResponseEntity.ok(ApiResponse.success(classes));
    }
    
    /**
     * 检查班级是否存在
     */
    @GetMapping("/{classesId}/exists")
    public ResponseEntity<ApiResponse<Boolean>> checkClassExists(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId) {
        boolean exists = classesService.existsByClassesId(classesId);
        return ResponseEntity.ok(ApiResponse.success(exists));
    }
    
    /**
     * 检查班级名称是否存在
     */
    @GetMapping("/name/{classesName}/exists")
    public ResponseEntity<ApiResponse<Boolean>> checkClassNameExists(
            @PathVariable @NotBlank(message = "班级名称不能为空") String classesName) {
        boolean exists = classesService.existsByClassesName(classesName);
        return ResponseEntity.ok(ApiResponse.success(exists));
    }
    
    /**
     * 根据班级ID获取教师ID列表
     */
    @GetMapping("/{classesId}/teachers/ids")
    public ResponseEntity<ApiResponse<List<String>>> getTeacherIdsByClassId(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId) {
        List<String> teacherIds = classesService.getTeacherIdsByClassId(classesId);
        return ResponseEntity.ok(ApiResponse.success(teacherIds));
    }
    
    /**
     * 向班级添加学生
     */
    @PostMapping("/{classesId}/students/{userId}")
    public ResponseEntity<ApiResponse<Void>> addStudentToClass(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId,
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        classesService.addStudentToClass(classesId, userId);
        return ResponseEntity.ok(ApiResponse.success("学生添加成功"));
    }
    
    /**
     * 从班级移除学生
     */
    @DeleteMapping("/{classesId}/students/{userId}")
    public ResponseEntity<ApiResponse<Void>> removeStudentFromClass(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId,
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        classesService.removeStudentFromClass(classesId, userId);
        return ResponseEntity.ok(ApiResponse.success("学生移除成功"));
    }
    
    /**
     * 向班级添加教师
     */
    @PostMapping("/{classesId}/teachers/{userId}")
    public ResponseEntity<ApiResponse<Void>> addTeacherToClass(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId,
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        classesService.addTeacherToClass(classesId, userId);
        return ResponseEntity.ok(ApiResponse.success("教师添加成功"));
    }
    
    /**
     * 从班级移除教师
     */
    @DeleteMapping("/{classesId}/teachers/{userId}")
    public ResponseEntity<ApiResponse<Void>> removeTeacherFromClass(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId,
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        classesService.removeTeacherFromClass(classesId, userId);
        return ResponseEntity.ok(ApiResponse.success("教师移除成功"));
    }
    
    /**
     * 检查学生是否在班级中
     */
    @GetMapping("/{classesId}/students/{userId}/exists")
    public ResponseEntity<ApiResponse<Boolean>> isStudentInClass(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId,
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        boolean exists = classesService.isStudentInClass(classesId, userId);
        return ResponseEntity.ok(ApiResponse.success(exists));
    }
    
    /**
     * 检查教师是否在班级中
     */
    @GetMapping("/{classesId}/teachers/{userId}/exists")
    public ResponseEntity<ApiResponse<Boolean>> isTeacherInClass(
            @PathVariable @NotBlank(message = "班级ID不能为空") String classesId,
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        boolean exists = classesService.isTeacherInClass(classesId, userId);
        return ResponseEntity.ok(ApiResponse.success(exists));
    }
    
    /**
     * 根据课程ID和用户ID获取用户作为教师的所有班级
     * 兼容单体系统API: GET /api/exercises/classes/teacher
     */
    @GetMapping("/course/{courseId}/teacher/{userId}")
    public ResponseEntity<ApiResponse<List<Classes>>> getClassesAsTeacher(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId,
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        List<Classes> classes = classesService.getClassesAsTeacher(courseId, userId);
        return ResponseEntity.ok(ApiResponse.success(classes));
    }
    
    /**
     * 根据课程ID和用户ID获取班级ID
     * 兼容单体系统API: GET /api/exercises/classes-id
     */
    @GetMapping("/course/{courseId}/user/{userId}/id")
    public ResponseEntity<ApiResponse<String>> getClassesIdByCourseAndUser(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId,
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        String classesId = classesService.getClassesIdByCourseAndUser(courseId, userId);
        return ResponseEntity.ok(new ApiResponse<>(200, "Success", classesId, System.currentTimeMillis()));
    }
}